import sys
sys.path.append("../")
sys.path.append(".")
from predicter import CommonPredicter

message_dic={'200':'正常',
             '300':'请求格式错误',
             '400':'模型预测失败'}

class ModelServer:
    def __init__(self, predicter, args):
        self.predict = predicter.predict

    def parse(self, app_data):
        request_id = app_data["request_id"]
        texts = app_data["query"]
        return request_id, texts

    def get_result(self,data):
        code = '200'
        try:
            request_id, texts = self.parse(data) 
        except Exception as e:
            print('error info : {}'.format(e))
            code='300'
            request_id = "None"
        try:
            if code == '200':
                label = self.predict(texts)
            elif code == '300':
                label = None
        except Exception as e:
            print('error info : {}'.format(e))
            label = None
            code='400'

        result = {'label': label,'code':code,'message':message_dic[code],'request_id':request_id}  
        return result

    def get_result_of_text(self,texts: list):
        if type(texts) == str: texts = [texts]
        code = '200'
        try:
            if code == '200':
                label = self.predict(texts)
            elif code == '300': label = None
        except Exception as e:
            print('error info : {}'.format(e))
            label = None
            code='400'

        result = {'label': label,'code':code,'message':message_dic[code]}  
        return result


def test1(args):
    predicter = CommonPredicter.init(args)
    server = ModelServer(predicter=predicter, args=args)
    data = {"request_id": "ExamServer", 
            "query" :["菠菜从土壤中吸收的氮元素可以用来合成（）A.淀粉和纤维素B.葡萄糖和DNAC.核酸和蛋白质D.麦芽糖和脂肪酸"]}
    print("\n The result is {}".format(server.get_result(data)))

def test2(args):
    predicter = CommonPredicter.init(args)
    server = ModelServer(predicter=predicter, args=args)
    texts = ["菠菜从土壤中吸收的氮元素可以用来合成（）A.淀粉和纤维素B.葡萄糖和DNAC.核酸和蛋白质D.麦芽糖和脂肪酸"]
    print(f"The result is {server.get_result_of_text(texts)}")

if __name__ == "__main__":
    from parse import args
    test2(args)